package org.linlinjava.litemall.db.service.wechat_notice;


import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.linlinjava.litemall.db.dao.*;
import org.linlinjava.litemall.db.dao.order_manage.AgedmallServiceOrderManageMapper;
import org.linlinjava.litemall.db.dao.order_manage.AgedmallShopMapper;
import org.linlinjava.litemall.db.domain.*;
import org.linlinjava.litemall.db.util.*;
import org.linlinjava.litemall.db.vo.logistics.LogisticsCommonData;
import org.linlinjava.litemall.db.vo.service_order.ServiceOrderDetailBackDto;
import org.linlinjava.litemall.db.vo.wechat.ApplicationCardMessage;
import org.linlinjava.litemall.db.vo.wechat.GoodsMessage;
import org.linlinjava.litemall.db.vo.wechat.SeparateWechatData;
import org.linlinjava.litemall.db.vo.wechat.TextCardDescMessage;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;

/**
 * @author wj
 * @date 2021/10/15 14:38
 */
@Service
public class WechatNoticeService {

    @Resource
    private AgedmallTakeOrderRecordMapper agedmallTakeOrderRecordMapper;

    @Resource
    private AgedmallLogisticsPackageInfoMapper agedmallLogisticsPackageInfoMapper;

    @Resource
    private AgedmallPrintOrderMapper agedmallPrintOrderMapper;

    @Resource
    private LitemallOrderGoodsMapper litemallOrderGoodsMapper;

    @Resource
    private AgedmallShopMapper agedmallShopMapper;

    @Resource
    private AgedmallDeliveryManInfoMapper agedmallDeliveryManInfoMapper;

    @Resource
    private AgedmallReturnGoodsRecordMapper agedmallReturnGoodsRecordMapper;

    @Resource
    private AgedmallLeaseGoodsReturnRecordMapper agedmallLeaseGoodsReturnRecordMapper;

    @Resource
    private AgedmallWechatGroupMapper agedmallWechatGroupMapper;

    @Resource
    private AgedmallDoctorInfoMapper agedmallDoctorInfoMapper;

    @Resource
    private AgedmallServiceOrderMapper agedmallServiceOrderMapper;

    @Resource
    private AgedmallServiceOrderManageMapper agedmallServiceOrderManageMapper;

    @Resource
    private AgedmallLgBaseInfoMapper agedmallLgBaseInfoMapper;

    @Resource
    private AgedmallLgMissionMapper agedmallLgMissionMapper;

    @Resource
    private WechatUtil wechatUtil;


    /**
     * 添加
     * @param id 打印订单表id
     * @param ids 配送员id集合
     * @param type 类型（0-顺序接单 1-抢单）
     * @param messageType 发送类型（0-配货 1-送货 2-取货 3-维护）
     * @return
     */
    public List<AgedmallTakeOrderRecord> add(Integer id,List<Integer> ids,Integer type,Integer messageType){
        List<AgedmallTakeOrderRecord> takeOrderRecordArrayList=new ArrayList<>();
        Collections.sort(ids);
        for (int i = 0; i < ids.size(); i++) {
            AgedmallTakeOrderRecord takeOrderRecord=new AgedmallTakeOrderRecord();
            takeOrderRecord.setPrintId(id);
            takeOrderRecord.setDeliveryManId(ids.get(i));
            takeOrderRecord.setType(type);
            takeOrderRecord.setMessageType(messageType);
            takeOrderRecord.setState(0);
            takeOrderRecord.setAddTime(LocalDateTime.now());
            agedmallTakeOrderRecordMapper.insertSelective(takeOrderRecord);
            takeOrderRecordArrayList.add(takeOrderRecord);
        }
        return takeOrderRecordArrayList;
    }


    /**
     * 发送消息-发送给个人-按钮模板    （组装数据+更新状态）
     * @param id
     */
    public ApplicationCardMessage sendNotice(Long id){
        AgedmallTakeOrderRecord record=agedmallTakeOrderRecordMapper.selectByPrimaryKey(id);
        record.setState(1);
        AgedmallLgMission mission=agedmallLgMissionMapper.selectByPrimaryKey(record.getPrintId());
        AgedmallLgBaseInfo agedmallLgBaseInfo = agedmallLgBaseInfoMapper.selectByPrimaryKey(mission.getBaseInfoId().longValue());
        LogisticsCommonData commonData = LogisticsGoodsUtil.parseObject(agedmallLgBaseInfo.getLgContent());
        ApplicationCardMessage applicationCardMessage = LogisticsGoodsUtil.commonDataToApplicationCard(commonData, record.getMessageType());

        applicationCardMessage.setType(record.getMessageType());
        applicationCardMessage.setTakeOrderId(id.intValue());
        if(record.getMessageType()==4){
            List<ServiceOrderDetailBackDto> serviceOrderDetailList = agedmallServiceOrderManageMapper.getServiceOrderDetailList(record.getPrintId());
            if(!serviceOrderDetailList.isEmpty()){
                applicationCardMessage.setDepartmentName(serviceOrderDetailList.get(0).getDepartmentName());
                applicationCardMessage.setServiceName(serviceOrderDetailList.get(0).getServiceName());
                applicationCardMessage.setServiceTime(serviceOrderDetailList.get(0).getTime());
            }
            AgedmallDoctorInfo agedmallDoctorInfo = agedmallDoctorInfoMapper.selectByPrimaryKey(record.getDeliveryManId().longValue());
            applicationCardMessage.setToUser(agedmallDoctorInfo.getWechatId());
        }
        else{
            AgedmallDeliveryManInfo agedmallDeliveryManInfo = agedmallDeliveryManInfoMapper.selectByPrimaryKey(record.getDeliveryManId());
            applicationCardMessage.setToUser(agedmallDeliveryManInfo.getWechatId());
        }
        agedmallTakeOrderRecordMapper.updateByPrimaryKey(record);
        return applicationCardMessage;
    }


    /**
     * 发送消息-群消息-卡片消息    （组装数据）
     * @param id
     */
    public TextCardDescMessage sendTextCardMessage(Long id){
        AgedmallTakeOrderRecord record=agedmallTakeOrderRecordMapper.selectByPrimaryKey(id);
        AgedmallLgMission mission=agedmallLgMissionMapper.selectByPrimaryKey(record.getPrintId());
        AgedmallLgBaseInfo agedmallLgBaseInfo = agedmallLgBaseInfoMapper.selectByPrimaryKey(mission.getBaseInfoId().longValue());
        LogisticsCommonData commonData = LogisticsGoodsUtil.parseObject(agedmallLgBaseInfo.getLgContent());
        TextCardDescMessage textCardDescMessage = LogisticsGoodsUtil.commonDataToTextCardDesc(commonData, record.getMessageType());
        String weChatUrlLink = wechatUtil.getWeChatUrlLink();
        textCardDescMessage.setWechatUrl(weChatUrlLink);
        Integer wechatGroupId;
        if(record.getMessageType()==4){
            List<ServiceOrderDetailBackDto> serviceOrderDetailList = agedmallServiceOrderManageMapper.getServiceOrderDetailList(record.getPrintId());
            if(!serviceOrderDetailList.isEmpty()){
                textCardDescMessage.setDepartmentName(serviceOrderDetailList.get(0).getDepartmentName());
                textCardDescMessage.setServiceName(serviceOrderDetailList.get(0).getServiceName());
                textCardDescMessage.setServiceTime(serviceOrderDetailList.get(0).getTime());
                textCardDescMessage.setUserName(serviceOrderDetailList.get(0).getUserName());
                textCardDescMessage.setUserPhone(serviceOrderDetailList.get(0).getUserPhone());
            }
            AgedmallDoctorInfo doctorInfo=agedmallDoctorInfoMapper.selectByPrimaryKey(record.getDeliveryManId().longValue());
            wechatGroupId=doctorInfo.getWechatGroupId();
        }
        else{
            AgedmallDeliveryManInfo agedmallDeliveryManInfo = agedmallDeliveryManInfoMapper.selectByPrimaryKey(record.getDeliveryManId());
            wechatGroupId=agedmallDeliveryManInfo.getWechatGroupId();
        }
            AgedmallWechatGroup wechatGroup = agedmallWechatGroupMapper.selectByPrimaryKey(wechatGroupId);
            textCardDescMessage.setChatId(wechatGroup.getGroupId().toString());
        return textCardDescMessage;
    }

    /**
     * 发送消息-群消息-文字消息    （判断文字）
     */
    public String switchTextMessage(Integer messageType){
        switch (messageType){
            case 2:
                return "恭喜您成功抢单，请及时取货";
            case 3:
                return "恭喜您成功抢单，请及时维护";
            case 4:
                return "恭喜您成功抢单";
            case 0:
            case 1:
            default:
                return "恭喜您成功抢单，请及时配送";
        }
    }


    /**
     *   拒绝/超时拒绝
     * @param id 主键id
     * @param isTimeOut
     * @return
     */
    public Long refused(Long id,boolean isTimeOut){
        AgedmallTakeOrderRecord agedmallTakeOrderRecord = agedmallTakeOrderRecordMapper.selectByPrimaryKey(id);
        if(isTimeOut){
            agedmallTakeOrderRecord.setState(4);
        }
        else {
            agedmallTakeOrderRecord.setState(2);
        }
        agedmallTakeOrderRecordMapper.updateByPrimaryKeySelective(agedmallTakeOrderRecord);
        if(agedmallTakeOrderRecord.getType()==0){
            AgedmallTakeOrderRecordExample nextExample=new AgedmallTakeOrderRecordExample();
            nextExample.setOrderByClause("add_time ASC,`delivery_man_id` asc");
            nextExample.or().andPrintIdEqualTo(agedmallTakeOrderRecord.getPrintId());
            List<AgedmallTakeOrderRecord> orderRecordList = agedmallTakeOrderRecordMapper.selectByExample(nextExample);
            AgedmallTakeOrderRecord nextUser=new AgedmallTakeOrderRecord();
            for (int i = 0; i < orderRecordList.size(); i++) {
                if(orderRecordList.get(i).getId().equals(id)&&i+1<orderRecordList.size()
                &&orderRecordList.get(i+1).getState()==0){
                    nextUser=orderRecordList.get(i+1);
                }
            }
            return nextUser.getId();
        }
        return null;
    }



    /**
     *  同意接单
     * @param id
     * @return
     */
    public Object confirm(Long id){
        AgedmallTakeOrderRecordExample recordExample=new AgedmallTakeOrderRecordExample();
        recordExample.or().andIdEqualTo(id);
        AgedmallTakeOrderRecord orderRecord=new AgedmallTakeOrderRecord();
        orderRecord.setState(3);
        agedmallTakeOrderRecordMapper.updateByExampleSelective(orderRecord,recordExample);
        return "ok";
    }

    /**
     * 接单后对数据库数据进行同步
     * @param takeOrderId
     */
    public void changeDbTablesData(Long takeOrderId){
//        AgedmallTakeOrderRecord takeOrderRecord=agedmallTakeOrderRecordMapper.selectByPrimaryKey(takeOrderId);
//
//        //医生抢单
//        if(takeOrderRecord.getMessageType()==4){
//            AgedmallServiceOrder agedmallServiceOrder = agedmallServiceOrderMapper.selectByPrimaryKey(takeOrderRecord.getPrintId().longValue());
//            agedmallServiceOrder.setDoctorId(takeOrderRecord.getDeliveryManId().longValue());
//            agedmallServiceOrder.setStat(3);
//            agedmallServiceOrderMapper.updateByPrimaryKeySelective(agedmallServiceOrder);
//        }
//        else{
//            AgedmallLgBaseInfo lgBaseInfo=agedmallLgBaseInfoMapper.selectByPrimaryKey(takeOrderRecord.getPrintId().longValue());
//            //TODO 修改baseInfo相关表状态
//                    lgBaseInfo.setLgStat(LgBaseInfoStatConstant.getNowStat(lgBaseInfo.getLgType(),takeOrderRecord.getMessageType()));
//
//        }

    }

}
